<!-- eslint-disable vue/no-template-key -->
<!-- eslint-disable vue/valid-v-for -->
<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              type="text"
              class="text-btn-cursor"
              size="small"
              @click="lookDetailed(row)"
            >
              <i class="el-icon-view"></i>查看盘点详情
            </el-button>
            <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="addDetailed(row)"
            >
              <i class="el-icon-edit-outline"></i> 添加盘点详情
            </el-button>
            <!-- <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.stordocNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button> -->
          </template>
        </template>
        <!-- <template v-slot:enableStatus="{ row, item  }">
          <template v-if="!row.index">
            {{ (row[`${item.prop}`] === false ? '未启用' : row[`${item.prop}`] === true ? '已启用' : '——') || '——' }}
          </template>
        </template> -->
        <template v-slot:stordocName="{ row, item }">
          <template v-if="!row.index">
            {{ row.stordoc.stordocName || '——' }}
          </template>
        </template>
        <template v-slot:dcountDate="{ row, item  }">
          <template v-if="!row.index">
            {{ dateToFormattwo( row[`${item.prop}`]) || '——' }}
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          v-if="nowChanceStau === 'edit' || nowChanceStau === 'add'"
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            v-for="item,index in formDatalists"
            :key="index"
            :label="item.name + ':'"
            :prop="item.selectValue || item.prop"
            class="w50p"
            :rules="[
              { required: item.required, message: item.name + '不能为空', trigger: item.type === 'input' ? 'blur' : 'change'}
            ]"
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="formData[ `${item.prop}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="formData[ `${item.selectValue}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items[item.typeObj.listName[0]]"
                :value="items[item.typeObj.listName[1]]"
              />
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.prop}`]"
              type="date"
              value-format="timestamp"
              :placeholder="'选择' + item.name"
            />
          </el-form-item>
        </el-form>

        <el-form
          v-if="nowChanceStau === 'addDetails'"
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="物料:"
            :prop="'materialNo'"
            :rules="{
              required: true,
              message: '物料不能为空',
              trigger: 'change',
            }"
            class="w50p"
          >
            <el-select
              v-model="formData.materialNo"
              placeholder="选择物料"
              filterable
              clearable
              @change="queryOnHandQuantity"
            >
              <el-option
                v-for="item in materialList"
                :key="item.materialNo"
                :label="item.materialName"
                :value="item.materialNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="点击选择:"
            :prop="'batchObj'"
            :rules="{
              required: true,
              message: '不能为空',
              trigger: 'change',
            }"
            class="w50p"
          >
            <el-select
              v-model="formData.batchObj"
              placeholder="点击选择"
              filterable
              clearable
              value-key="onHandQuantityId"
              @change="batchObjChange"
            >
              <el-option
                v-for="item in handQuantityList"
                :key="item.onHandQuantityId"
                :label="'行号: ' + item.batchNo + ' 批号: ' + (item.batchFile.lotNumber === undefined ? '' : item.batchFile.lotNumber) + ' 单位: ' + item.castUnit.symbol + ' 换算率 : ' + item.changerate+ ' 生产日期 : ' + item.batchFile.produceDate+ ' 	失效日期 : ' + item.batchFile.expirationDate"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" class="w50p">
            <el-form-item style="width: 70%">
              <el-input v-model="formData.num" disabled />
            </el-form-item>
            <el-form-item style="width: 30%">
              <el-input v-model="formData.casymbol" disabled />
            </el-form-item>
          </el-form-item>
          <el-form-item label="换算率" class="w50p">
            <el-input v-model="formData.changerate" disabled />
          </el-form-item>
          <el-form-item label="账面数量" class="w50p">
            <el-form-item style="width: 70%">
              <el-input v-model="formData.nonhandastNum" disabled />
            </el-form-item>
            <el-form-item style="width: 30%">
              <el-input v-model="formData.symbol" disabled />
            </el-form-item>
          </el-form-item>
          <el-form-item label="盘点数量" prop="ncountastNum"
            :rules="[{
              required: true,
              message: '盘点数量不能为空',
              trigger: 'change',
            },{ pattern: /^[+]?(\d+)$|^[+]?(\d+\.\d+)$/, message:'值为不小于0的数', trigger: ['change','blur']}]"class="w50p">
            <el-form-item
              prop="ncountastNum"
              style="width: 70%"
            >
              <el-input
                v-model="formData.ncountastNum"
                clearable
                placeholder="请输入盘点数量"
              />
            </el-form-item>
            <el-form-item style="width: 30%">
              <el-input v-model="formData.casymbol" disabled />
            </el-form-item>
          </el-form-item>
          <el-form-item label="差异数量" class="w50p">
            <el-input v-model="formData.ndiffastNum" clearable />
          </el-form-item>
          <el-form-item label="原因" class="w50p">
            <el-input v-model="formData.reason" placeholder="请输入原因" clearable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau === 'lookDetails'">
          <el-descriptions
            v-for="item in lookDetailList"
            :key="item.invcountNo"
            class="margin-top"
            :title=" '物料：' + item.material.materialName"
            :column="3"
            :size="'medium'"
          >
            <el-descriptions-item label="行号">{{ item.batchNo }}</el-descriptions-item>
            <el-descriptions-item label="批号">{{ item.batchFile.lotNumber }}</el-descriptions-item>
            <el-descriptions-item label="生产日期">{{ item.batchFile.produceDate }}</el-descriptions-item>
            <el-descriptions-item
              label="失效日期"
            >{{ item.batchFile.expirationDate }}</el-descriptions-item>
            <el-descriptions-item
              label="数量"
            >{{ item.num }}{{ item.castUnit.symbol }}</el-descriptions-item>
            <el-descriptions-item label="换算率">{{ item.changerate }}</el-descriptions-item>
            <el-descriptions-item
              label="账面数量"
            >{{ item.nonhandastNum }}{{ item.cUnit.symbol }}</el-descriptions-item>
            <el-descriptions-item
              label="盘点数量"
            >{{ item.ncountastNum }}{{ item.castUnit.symbol }}</el-descriptions-item>
            <el-descriptions-item label="原因" :span="24">{{ item.reason|| '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div
          v-if="nowChanceStau === 'add' || nowChanceStau === 'addDetails'"
          slot="footer"
          class="dialog-footer"
        >
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import inventoryApi from "@/api/livestock-manage/storage-manage/inventory-records";
import inventorySetailsApi from "@/api/livestock-manage/storage-manage/inventory-records-details";
import quantityApi from "@/api/livestock-manage/storage-manage/quantity-on-hand";
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage";
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage";
// css for then
export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: '仓库名称',
          prop: 'stordocNo',
          type: 'select',
          options: [],
          optionKey: { label: 'stordocName', value: 'stordocNo' },
        },
        {
          label: '仓库管员',
          prop: 'cwhsmanagerName',
          type: 'select',
          options: [],
          optionKey: { label: 'name', value: 'name' },
        },
        {
          label: '盘点人',
          prop: 'countoperatorName',
          type: 'select',
          options: [],
          optionKey: { label: 'name', value: 'name' },
        },
        {
          label: '盘点日期',
          prop: 'dcountDate',
          type: 'date',
        },
      ],
      selectedStaffList: [],
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "stordocName",
          porpObj: "stordoc",
          selectValue: "stordocNo",
          typeObj: {},
          name: "仓库",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "cwhsmanagerName",
          selectValue: "cwhsmanagerName",
          typeObj: {},
          name: "仓库管员",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "countoperatorName",
          selectValue: "countoperatorName",
          typeObj: {},
          name: "盘点人",
          required: true
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "dcountDate",
          selectValue: "",
          typeObj: {},
          name: "盘点日期",
          required: true,
          notSearch: true
        }
      ],
      formDataDetails: {},
      materialList: [],
      handQuantityList: [],
      lookDetailList: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.num && val.nonhandastNum) {
          this.$set(
            val,
            "ndiffastNum",
            isNaN(val.ncountastNum - val.num) ? "" : val.ncountastNum - val.num
          );
        }
      }
    }
  },
  created() {
    let list = []
    this.formDatalists.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px'
      }
      if (['enableStatus', 'stordocName', 'dcountDate'].includes(el.prop)) {
        obj.slotName = el.prop
      }
      list.push(obj)
    })
    list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '260' })
    this.tableColumn = list
    console.log(this.tableColumn)

    this.search();
    this.getPerson();
    this.getstordocList();
  },
  methods: {
    // 获取记录人列表
    getPerson() {
      personApi.getStaffListByCondition().then(res => {
        if (res.code === 1) {
          let list = [];
          this.personList = res.data || [];
          res.data.forEach(item => {
            list.push({
              name: item.person.name,
              value: item.personNo
            });
          });
          this.formDatalists.forEach((item, index) => {
            if (
              item.prop === "cwhsmanagerName" ||
              item.prop === "countoperatorName"
            ) {
              this.$set(this.formDatalists[index], "typeObj", {
                list: list,
                listName: ["name", "name"]
              });
            }
          });
          this.setOptions(this.formConfig, 'cwhsmanagerName', list)
          this.setOptions(this.formConfig, 'countoperatorName', list)
        }
      });
    },
    // 获取盘点
    getstordocList() {
      warehouseApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          this.stordocList = res.data;
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "stordocName") {
              this.$set(this.formDatalists[index], "typeObj", {
                list: res.data,
                listName: ["stordocName", "stordocNo"]
              });
            }
          });
          this.setOptions(this.formConfig, 'stordocNo', res.data)
        }
      });
    },
    getMaterialType(e) {
      quantityApi.queryCheckNo(e).then(res => {
        this.materialList = res.data;
      });
    },
    batchObjChange(e) {
      // this.$set()
      let formData = { ...this.formData };
      this.$set(formData, "symbol", e.cUnit.symbol);
      this.$set(formData, "casymbol", e.castUnit.symbol);
      this.$set(formData, "nonhandastNum", e.onHandQuantity);
      this.formData = { ...formData, ...e };
      console.log(e);
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchlist,
          dcountDate: this.searchlist.dcountDate && this.searchlist.dcountDate+' 00:00'
        }
      };
      inventoryApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.invcountNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      inventoryApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          inventoryApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = {};
      this.nowChanceStau = "add";
      this.titleText = "添加盘点";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = {
        ...row,
        dcountDate: new Date(row.dcountDate).getTime()
      };
      this.nowChanceStau = "edit";
      this.titleText = "修改盘点";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    addDetailed(row) {
      this.formData = { ...row };
      this.getMaterialType(row.stordocNo);
      this.nowChanceStau = "addDetails";
      this.titleText = "添加盘点详情";
      this.dialogFormVisible = true;
      // this.addCountList();
    },
    async lookDetailed(e) {
      const { data: res } = await inventorySetailsApi.conditionQuery({
        invcountNo: e.invcountNo
      });
      this.lookDetailList = res;

      this.nowChanceStau = "lookDetails";
      this.titleText = "查看盘点详情";
      this.dialogFormVisible = true;
    },
    async queryOnHandQuantity(e) {
      if (this.formData.stordocNo && this.formData.invcountNo && e) {
        const { data: res } = await inventorySetailsApi.queryOnHandQuantity(
          this.formData.invcountNo,
          e,
          this.formData.stordocNo
        );
        this.handQuantityList = res;
      } else if (e) {
        this.$message.warning("请重新选择物料");
      }
    },
    save(formData) {
      // console.log(this.formData);
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let formData = { ...this.formData };
            inventoryApi.edit(formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let person = { ...this.formData };
            inventoryApi.add(person).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          } else if (this.nowChanceStau === "addDetails") {
            let person = {
              batchNo: this.formData.batchNo,
              castUnitNo: this.formData.castUnitNo,
              changerate: this.formData.changerate,
              createName: this.formData.createName,
              invcountNo: this.formData.invcountNo,
              materialNo: this.formData.materialNo,
              ncountastNum: this.formData.ncountastNum,
              ndiffastNum: this.formData.ndiffastNum,
              nonhandastNum: this.formData.nonhandastNum,
              num: this.formData.num,
              organizationNo: this.formData.organizationNo,
              reason: this.formData.reason,
              stordocNo: this.formData.stordocNo,
              unitNo: this.formData.unitNo,
              updateName: this.formData.updateName
            };
            inventorySetailsApi.add(person).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                // this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep {
  .el-descriptions {
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.2);
    margin-bottom: 20px;
  }
  .el-descriptions__body {
    padding: 5px;
    border-radius: 5px;
    .el-descriptions-item__container {
      font-weight: 900;
      font-size: 16px;
    }
  }
}

.line-click {
  width: 30px;
  height: 30px;
  background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  border: rgb(214, 214, 214) 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
  .el-icon-plus {
    color: white;
  }
}
.line-clicks {
  width: 30px;
  height: 30px;
  // background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  // border: rgb(214, 214, 214) 1px solid;
  color: red;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  text-decoration: underline;
  text-underline-position: under;
  position: relative;
  right: 0;
  top: 0;
  cursor: pointer;
}
::v-deep .el-dialog {
  .el-dialog__body {
    max-height: 65vh;
  }
}
.addE {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  // padding: 0 2%;
}
</style>
